﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio
Copyright (c) 2011,      Zynga Inc.
Copyright (c) 2008-2010, Ricardo Quesada

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

TMX Tiled Map support:
	http://www.mapeditor.org
*******************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;

namespace PKEngine
{
	/// <summary>
	/// PKTmxTiledMap knows how to parse and render a TMX map.
	/// 	- It only supports one tileset per layer.
	/// 	- Embeded images are not supported.
	/// 	- It only supports the XML format. (the JSON format is not supported)
	/// 	- It only supports the orthogonal orientation map.
	/// </summary>
	public class PKTmxTiledMap : PKNode
	{
		#region Private Fields
		private Dictionary<int, Dictionary<string, string>> tileProperties;
		#endregion

		#region Public Properties
		/// <summary>
		/// Properties for the map.
		/// </summary>
		public Dictionary<string, string> Properties { get; private set; }

		/// <summary>
		/// Object Groups.
		/// </summary>
		public List<PKTmxObjectGroup> ObjectGroups { get; private set; }

		/// <summary>
		/// The map's size property measured in tiles.
		/// </summary>
		public Size MapSize { get; set; }

		/// <summary>
		/// The tiles's size property measured in pixels.
		/// </summary>
		public Size TileSize { get; set; }
		#endregion

		#region Initialization
		private void Initialize(PKTmxMapInfo mapInfo)
		{
			this.MapSize = mapInfo.MapSize;
			this.TileSize = mapInfo.TileSize;
			this.ObjectGroups = mapInfo.ObjectGroups;
			this.Properties = mapInfo.Properties;
			this.tileProperties = mapInfo.TileProperties;

			int index = 0;
			foreach (PKTmxLayerInfo layerInfo in mapInfo.Layers)
			{
				if (layerInfo.IsVisible)
				{
					PKTmxLayer layer = ParseLayer(layerInfo, mapInfo);
					this.AddChild(layer, index, index);

					Size childSize = layer.ContentSize;
					Size currentSize = this.ContentSize;
					currentSize.Width = Math.Max(currentSize.Width, childSize.Width);
					currentSize.Height = Math.Max(currentSize.Height, childSize.Height);
					this.ContentSize = currentSize;

					index++;
				}
			}
		}

		public static PKTmxTiledMap MapMake(string tmxFile)
		{
			return new PKTmxTiledMap().Init(tmxFile);
		}

		public static PKTmxTiledMap MapMake(string tmxText, string resourcePath)
		{
			return new PKTmxTiledMap().Init(tmxText, resourcePath);
		}

		public PKTmxTiledMap Init(string tmxFile)
		{
			Debug.Assert(!string.IsNullOrEmpty(tmxFile), "PKTmxTiledMap: Argument cannot be null.");
			Debug.Assert(File.Exists(tmxFile), "PKTmxTiledMap: Cannot find file.");

			PKTmxMapInfo mapInfo = new PKTmxMapInfo(tmxFile);
			Debug.Assert(mapInfo.Tilesets.Count != 0, "PKTmxTiledMap: Cannot load map correctly: " + tmxFile);

			this.Initialize(mapInfo);

			return this;
		}

		public PKTmxTiledMap Init(string tmxText, string resourcePath)
		{
			Debug.Assert(!string.IsNullOrEmpty(tmxText), "PKTmxTiledMap: Argument cannot be null.");
			Debug.Assert(Directory.Exists(resourcePath), "PKTmxTiledMap: Cannot find path.");

			PKTmxMapInfo mapInfo = new PKTmxMapInfo(tmxText, resourcePath);
			Debug.Assert(mapInfo.Tilesets.Count != 0, "PKTmxTiledMap: Cannot load map correctly: " + tmxText);

			this.Initialize(mapInfo);

			return this;
		}
		#endregion

		#region Public Methods
		public PKTmxLayer LayerNamed(string name)
		{
			foreach (PKNode node in Children)
			{
				PKTmxLayer layer = node as PKTmxLayer;
				if (layer != null && layer.LayerName == name)
				{
					return layer;
				}
			}
			return null;
		}

		public PKTmxObjectGroup ObjectGroupNamed(string name)
		{
			foreach (PKTmxObjectGroup objectGroup in ObjectGroups)
			{
				if (objectGroup.GroupName == name)
				{
					return objectGroup;
				}
			}
			return null;
		}

		public string PropertyNamed(string name)
		{
			return Properties[name];
		}

		public Dictionary<string, string> GetPropertiesForGId(int gid)
		{
			return tileProperties[gid];
		}
		#endregion

		#region Private Methods
		private static PKTmxLayer ParseLayer(PKTmxLayerInfo layerInfo, PKTmxMapInfo mapInfo)
		{
			PKTmxTilesetInfo tilesetInfo = GetTilesetForLayer(layerInfo, mapInfo);
			PKTmxLayer layer = new PKTmxLayer(tilesetInfo, layerInfo, mapInfo);
			layer.SetupTiles();
			return layer;
		}

		private static PKTmxTilesetInfo GetTilesetForLayer(PKTmxLayerInfo layerInfo, PKTmxMapInfo mapInfo)
		{
			Size size = layerInfo.LayerSize;

			for (int index = mapInfo.Tilesets.Count - 1; index >= 0; index--)
			{
				PKTmxTilesetInfo tilesetInfo = mapInfo.Tilesets[index];
				for (int y = 0; y < size.Height; y++)
				{
					for (int x = 0; x < size.Width; x++)
					{
						int pos = x + y * size.Width;
						int gid = layerInfo.Tiles[pos];

						if (gid != 0)
						{
							if (gid >= tilesetInfo.FirstGId)
							{
								return tilesetInfo;
							}
						}
					}
				}
			}

			Debug.Print("PKTmxTiledMap.GetTilesetForLayer: TmxLayer has no tileset: {0}", layerInfo.Name);
			return null;
		}
		#endregion
	}
}
